<template>
  <el-drawer
    v-model="visible"
    title="导航设置"
    :size="400"
    direction="rtl"
  >
    <div class="navigation-settings">
      <!-- 导航模式选择 -->
      <div class="setting-section">
        <h4>导航模式</h4>
        <div class="nav-mode-grid">
          <div
            v-for="mode in navigationModes"
            :key="mode.value"
            class="nav-mode-card"
            :class="{ active: currentMode === mode.value }"
            @click="changeNavigationMode(mode.value)"
          >
            <div class="mode-preview">
              <img :src="mode.icon" :alt="mode.name" />
            </div>
            <div class="mode-info">
              <div class="mode-name">{{ mode.name }}</div>
              <div class="mode-desc">{{ mode.description }}</div>
            </div>
            <div v-if="currentMode === mode.value" class="mode-badge">
              <el-icon><Check /></el-icon>
            </div>
          </div>
        </div>
      </div>

      <!-- 侧边栏设置 -->
      <div class="setting-section" v-if="showSidebarSettings">
        <h4>侧边栏设置</h4>
        <div class="setting-item">
          <span>侧边栏位置</span>
          <el-radio-group v-model="sidebarPosition" @change="updateSettings">
            <el-radio-button label="left">左侧</el-radio-button>
            <el-radio-button label="right">右侧</el-radio-button>
          </el-radio-group>
        </div>
        <div class="setting-item">
          <span>侧边栏宽度</span>
          <el-slider v-model="sidebarWidth" :min="200" :max="320" @change="updateSettings" />
          <span class="value-label">{{ sidebarWidth }}px</span>
        </div>
        <div class="setting-item">
          <span>自动收起</span>
          <el-switch v-model="autoCollapse" @change="updateSettings" />
        </div>
        <div class="setting-item">
          <span>显示图标</span>
          <el-switch v-model="showIcons" @change="updateSettings" />
        </div>
      </div>

      <!-- 顶部导航设置 -->
      <div class="setting-section" v-if="showTopBarSettings">
        <h4>顶部导航设置</h4>
        <div class="setting-item">
          <span>显示面包屑</span>
          <el-switch v-model="showBreadcrumb" @change="updateSettings" />
        </div>
        <div class="setting-item">
          <span>显示标签页</span>
          <el-switch v-model="showTabs" @change="updateSettings" />
        </div>
        <div class="setting-item">
          <span>固定顶部</span>
          <el-switch v-model="fixedHeader" @change="updateSettings" />
        </div>
      </div>

      <!-- 主题设置 -->
      <div class="setting-section">
        <h4>主题设置</h4>
        <div class="setting-item">
          <span>主题色</span>
          <el-color-picker v-model="themeColor" @change="updateSettings" />
        </div>
        <div class="setting-item">
          <span>暗黑模式</span>
          <el-switch v-model="darkMode" @change="updateSettings" />
        </div>
        <div class="setting-item">
          <span>紧凑模式</span>
          <el-switch v-model="compactMode" @change="updateSettings" />
        </div>
      </div>

      <!-- 快捷键设置 -->
      <div class="setting-section">
        <h4>系统快捷键</h4>
        <div class="shortcut-list">
          <div class="shortcut-item" v-for="shortcut in shortcuts" :key="shortcut.key">
            <span>{{ shortcut.name }}</span>
            <el-tag size="small">{{ shortcut.key }}</el-tag>
          </div>
        </div>
      </div>

      <!-- 自定义快捷方式 -->
      <div class="setting-section">
        <div class="section-header">
          <h4>我的快捷方式</h4>
          <el-button type="primary" size="small" @click="showAddShortcut = true">
            <el-icon><Plus /></el-icon>
            添加
          </el-button>
        </div>
        <div class="custom-shortcuts-list">
          <div
            v-for="(item, index) in customShortcuts"
            :key="index"
            class="custom-shortcut-item"
          >
            <div class="shortcut-icon" :style="{ background: item.color }">
              <el-icon :size="20">
                <component :is="getIconComponent(item.icon)" />
              </el-icon>
            </div>
            <div class="shortcut-info">
              <div class="shortcut-name">{{ item.name }}</div>
              <div class="shortcut-path">{{ item.path }}</div>
            </div>
            <div class="shortcut-actions">
              <el-button link type="primary" size="small" @click="handleEditShortcut(item, index)">
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button link type="danger" size="small" @click="handleDeleteShortcut(index)">
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
          <el-empty v-if="customShortcuts.length === 0" description="暂无快捷方式，添加一个吧" :image-size="60" />
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="setting-actions">
        <el-button type="primary" @click="saveSettings" :loading="saving">
          保存设置
        </el-button>
        <el-button @click="resetSettings">
          恢复默认
        </el-button>
      </div>
    </div>

    <!-- 添加/编辑快捷方式对话框 -->
    <el-dialog
      v-model="showAddShortcut"
      :title="editingIndex >= 0 ? '编辑快捷方式' : '添加快捷方式'"
      width="500px"
    >
      <el-form :model="shortcutForm" :rules="shortcutRules" ref="shortcutFormRef" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="shortcutForm.name" placeholder="如：销售订单" />
        </el-form-item>
        <el-form-item label="路径" prop="path">
          <el-input v-model="shortcutForm.path" placeholder="如：/sales/orders">
            <template #prepend>/</template>
          </el-input>
          <el-text size="small" type="info">输入页面路径，如：sales/orders</el-text>
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-select v-model="shortcutForm.icon" placeholder="选择图标" style="width: 100%">
            <el-option
              v-for="icon in iconOptions"
              :key="icon.value"
              :label="icon.label"
              :value="icon.value"
            >
              <div style="display: flex; align-items: center; gap: 8px;">
                <el-icon><component :is="getIconComponent(icon.value)" /></el-icon>
                <span>{{ icon.label }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="颜色" prop="color">
          <el-color-picker v-model="shortcutForm.color" show-alpha :predefine="predefineColors" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="shortcutForm.description" type="textarea" :rows="2" placeholder="快捷方式描述（选填）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddShortcut = false">取消</el-button>
        <el-button type="primary" @click="handleSaveShortcut">确定</el-button>
      </template>
    </el-dialog>
  </el-drawer>
</template>

<script setup>
import { ref, computed, watch, markRaw, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useNavigationStore } from '@/stores/navigation'
import { useShortcutsStore } from '@/stores/shortcuts'
import {
  Check, Plus, Edit, Delete,
  HomeFilled, ShoppingCart, Box, Money, UserFilled, DataBoard, Setting,
  Document, Calendar, TrendCharts, Collection, Reading, Trophy
} from '@element-plus/icons-vue'

// 导入SVG图标
import ClassicIcon from '@/assets/icons/navigation/classic.svg'
import TopbarIcon from '@/assets/icons/navigation/topbar.svg'
import WorkspaceIcon from '@/assets/icons/navigation/workspace.svg'
import CommandIcon from '@/assets/icons/navigation/command.svg'
import PieMenuIcon from '@/assets/icons/navigation/pie-menu.svg'
import DockIcon from '@/assets/icons/navigation/dock.svg'
import CardIcon from '@/assets/icons/navigation/card.svg'
import SmartSearchIcon from '@/assets/icons/navigation/smart-search.svg'
import Win10Icon from '@/assets/icons/navigation/win10.svg'
import Win8Icon from '@/assets/icons/navigation/win8.svg'
import FloatingPanelIcon from '@/assets/icons/navigation/floating-panel.svg'
import GestureIcon from '@/assets/icons/navigation/gesture.svg'
import AIAssistantIcon from '@/assets/icons/navigation/ai-assistant.svg'

// Props & Emits
const props = defineProps({
  modelValue: Boolean
})

const emit = defineEmits(['update:modelValue'])

// Store
const navigationStore = useNavigationStore()
const shortcutsStore = useShortcutsStore()

// 响应式数据
const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const saving = ref(false)
const currentMode = ref(navigationStore.mode || 'classic')

// 设置项初始化
const sidebarPosition = ref('left')
const sidebarWidth = ref(240)
const autoCollapse = ref(false)
const showIcons = ref(true)
const showBreadcrumb = ref(true)
const showTabs = ref(true)
const fixedHeader = ref(true)
const themeColor = ref('#409eff')
const darkMode = ref(false)
const compactMode = ref(false)

// 初始化
onMounted(() => {
  shortcutsStore.init()
  loadSettings()
})

// 加载设置
const loadSettings = () => {
  const store = navigationStore
  currentMode.value = store.mode || 'classic'
  sidebarPosition.value = store.settings?.sidebarPosition || 'left'
  sidebarWidth.value = store.settings?.sidebarWidth || 240
  autoCollapse.value = store.settings?.autoCollapse || false
  showIcons.value = store.settings?.showIcons ?? true
  showBreadcrumb.value = store.settings?.showBreadcrumb ?? true
  showTabs.value = store.settings?.showTabs ?? true
  fixedHeader.value = store.settings?.fixedHeader ?? true
  themeColor.value = store.settings?.themeColor || '#409eff'
  darkMode.value = store.settings?.darkMode || false
  compactMode.value = store.settings?.compactMode || false
}

// 监听drawer打开，每次打开时刷新设置
watch(visible, (newVal) => {
  if (newVal) {
    loadSettings()
  }
})

// 导航模式配置
const navigationModes = ref([
  {
    value: 'classic',
    name: '经典导航',
    description: '左侧边栏导航，适合层级较深的菜单',
    icon: ClassicIcon
  },
  {
    value: 'topbar',
    name: '顶部导航',
    description: '顶部+侧边栏，适合模块化应用',
    icon: TopbarIcon
  },
  {
    value: 'workspace',
    name: '工作台模式',
    description: '卡片式布局，适合多任务处理',
    icon: WorkspaceIcon
  },
  {
    value: 'command',
    name: '命令面板',
    description: '快捷键驱动，适合高效操作',
    icon: CommandIcon
  },
  {
    value: 'pie-menu',
    name: '圆形菜单',
    description: '创新的圆形菜单导航，炫酷高效',
    icon: PieMenuIcon,
    badge: 'NEW'
  },
  {
    value: 'dock',
    name: 'Dock栏导航',
    description: 'macOS风格的Dock栏，优雅美观',
    icon: DockIcon,
    badge: 'NEW'
  },
  {
    value: 'card',
    name: '卡片式导航',
    description: '大卡片展示，视觉冲击力强',
    icon: CardIcon,
    badge: 'NEW'
  },
  {
    value: 'smart-search',
    name: '智能搜索',
    description: '搜索驱动的导航方式，极速访问',
    icon: SmartSearchIcon,
    badge: 'HOT'
  },
  {
    value: 'win10',
    name: 'Windows 10 风格',
    description: '仿Windows 10开始菜单和任务栏',
    icon: Win10Icon,
    badge: 'NEW'
  },
  {
    value: 'win8',
    name: 'Windows 8 风格',
    description: '仿Windows 8开始屏幕和磁贴',
    icon: Win8Icon,
    badge: 'NEW'
  },
  {
    value: 'floating-panel',
    name: '浮动面板',
    description: '可拖拽的智能浮动导航面板',
    icon: FloatingPanelIcon,
    badge: '创新'
  },
  {
    value: 'gesture',
    name: '手势导航',
    description: '触摸手势和圆形菜单导航',
    icon: GestureIcon,
    badge: '创新'
  },
  {
    value: 'ai-assistant',
    name: 'AI助手',
    description: '智能AI助手驱动的导航体验',
    icon: AIAssistantIcon,
    badge: '未来'
  },
  {
    value: 'intelligent',
    name: '智能导航',
    description: 'AI驱动的智能导航系统，专为大型ERP优化',
    icon: AIAssistantIcon,
    badge: '推荐'
  },
  {
    value: 'smart-navigation',
    name: '智能导航系统',
    description: '类似图片中的导航方式，左侧主菜单+右侧子菜单',
    icon: AIAssistantIcon,
    badge: 'NEW'
  }
])

// 快捷键配置
const shortcuts = ref([
  { name: '打开命令面板', key: 'Ctrl + K' },
  { name: '全局搜索', key: 'Ctrl + /' },
  { name: '切换侧边栏', key: 'Ctrl + B' },
  { name: '返回首页', key: 'Ctrl + H' },
  { name: '关闭当前标签', key: 'Ctrl + W' }
])

// 自定义快捷方式
const showAddShortcut = ref(false)
const shortcutFormRef = ref(null)
const editingIndex = ref(-1)
const customShortcuts = computed(() => shortcutsStore.allShortcuts)

const shortcutForm = ref({
  name: '',
  path: '',
  icon: 'HomeFilled',
  color: '#409EFF',
  description: ''
})

const shortcutRules = {
  name: [{ required: true, message: '请输入快捷方式名称', trigger: 'blur' }],
  path: [{ required: true, message: '请输入页面路径', trigger: 'blur' }],
  icon: [{ required: true, message: '请选择图标', trigger: 'change' }]
}

// 图标选项
const iconOptions = [
  { label: '首页', value: 'HomeFilled' },
  { label: '购物车', value: 'ShoppingCart' },
  { label: '盒子', value: 'Box' },
  { label: '金钱', value: 'Money' },
  { label: '用户', value: 'UserFilled' },
  { label: '数据面板', value: 'DataBoard' },
  { label: '设置', value: 'Setting' },
  { label: '文档', value: 'Document' },
  { label: '日历', value: 'Calendar' },
  { label: '趋势图', value: 'TrendCharts' },
  { label: '收藏', value: 'Collection' },
  { label: '阅读', value: 'Reading' },
  { label: '奖杯', value: 'Trophy' }
]

// 预定义颜色
const predefineColors = [
  '#409EFF',
  '#67C23A',
  '#E6A23C',
  '#F56C6C',
  '#909399',
  'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
  'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
  'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
  'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)'
]

// 计算属性
const showSidebarSettings = computed(() => {
  return ['classic', 'topbar'].includes(currentMode.value)
})

const showTopBarSettings = computed(() => {
  return ['topbar', 'workspace'].includes(currentMode.value)
})

// 方法
const changeNavigationMode = (mode) => {
  currentMode.value = mode
  navigationStore.setMode(mode)
  ElMessage.success(`已切换到${navigationModes.value.find(m => m.value === mode)?.name}`)
}

const updateSettings = () => {
  const settings = {
    sidebarPosition: sidebarPosition.value,
    sidebarWidth: sidebarWidth.value,
    autoCollapse: autoCollapse.value,
    showIcons: showIcons.value,
    showBreadcrumb: showBreadcrumb.value,
    showTabs: showTabs.value,
    fixedHeader: fixedHeader.value,
    themeColor: themeColor.value,
    darkMode: darkMode.value,
    compactMode: compactMode.value
  }
  navigationStore.updateSettings(settings)
}

const saveSettings = async () => {
  saving.value = true
  
  // 模拟保存
  await new Promise(resolve => setTimeout(resolve, 1000))
  
  updateSettings()
  // localStorage 已由 navigationStore.saveToServer() 处理，不再需要手动保存
  
  saving.value = false
  ElMessage.success('设置已保存')
}

const resetSettings = async () => {
  currentMode.value = 'classic'
  sidebarPosition.value = 'left'
  sidebarWidth.value = 240
  autoCollapse.value = false
  showIcons.value = true
  showBreadcrumb.value = true
  showTabs.value = true
  fixedHeader.value = true
  themeColor.value = '#409eff'
  darkMode.value = false
  compactMode.value = false
  
  await navigationStore.resetSettings()
  
  ElMessage.success('已恢复默认设置')
}

// 获取图标组件
const getIconComponent = (iconName) => {
  const iconMap = {
    HomeFilled: markRaw(HomeFilled),
    ShoppingCart: markRaw(ShoppingCart),
    Box: markRaw(Box),
    Money: markRaw(Money),
    UserFilled: markRaw(UserFilled),
    DataBoard: markRaw(DataBoard),
    Setting: markRaw(Setting),
    Document: markRaw(Document),
    Calendar: markRaw(Calendar),
    TrendCharts: markRaw(TrendCharts),
    Collection: markRaw(Collection),
    Reading: markRaw(Reading),
    Trophy: markRaw(Trophy)
  }
  return iconMap[iconName] || markRaw(HomeFilled)
}

// 快捷方式管理
const handleEditShortcut = (item, index) => {
  editingIndex.value = index
  shortcutForm.value = { ...item }
  showAddShortcut.value = true
}

const handleDeleteShortcut = (index) => {
  ElMessageBox.confirm('确定要删除这个快捷方式吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    shortcutsStore.deleteShortcut(index)
    ElMessage.success('删除成功')
  }).catch(() => {})
}

const handleSaveShortcut = () => {
  shortcutFormRef.value.validate((valid) => {
    if (valid) {
      // 确保路径格式正确
      let path = shortcutForm.value.path
      if (!path.startsWith('/')) {
        path = '/' + path
      }

      const shortcutData = {
        name: shortcutForm.value.name,
        path: path,
        icon: shortcutForm.value.icon,
        color: shortcutForm.value.color,
        description: shortcutForm.value.description
      }

      if (editingIndex.value >= 0) {
        // 编辑
        shortcutsStore.updateShortcut(editingIndex.value, shortcutData)
        ElMessage.success('快捷方式已更新')
      } else {
        // 新增
        shortcutsStore.addShortcut(shortcutData)
        ElMessage.success('快捷方式已添加')
      }

      showAddShortcut.value = false
      editingIndex.value = -1
      
      // 重置表单
      shortcutForm.value = {
        name: '',
        path: '',
        icon: 'HomeFilled',
        color: '#409EFF',
        description: ''
      }
    }
  })
}

// 监听暗黑模式
watch(darkMode, (val) => {
  if (val) {
    document.documentElement.classList.add('dark')
  } else {
    document.documentElement.classList.remove('dark')
  }
})

// 监听主题色
watch(themeColor, (val) => {
  document.documentElement.style.setProperty('--el-color-primary', val)
})
</script>

<style scoped>
.navigation-settings {
  padding: 20px;
}

.setting-section {
  margin-bottom: 30px;
}

.setting-section h4 {
  margin: 0 0 16px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.nav-mode-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.nav-mode-card {
  position: relative;
  padding: 12px;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #fff;
}

.nav-mode-card:hover {
  border-color: #409eff;
  box-shadow: 0 2px 12px rgba(64, 158, 255, 0.15);
}

.nav-mode-card.active {
  border-color: #409eff;
  background: #ecf5ff;
}

.mode-preview {
  height: 60px;
  margin-bottom: 8px;
  background: #f5f7fa;
  border-radius: 4px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.mode-preview img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.mode-info {
  text-align: center;
}

.mode-name {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
  margin-bottom: 4px;
}

.mode-desc {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

.mode-badge {
  position: absolute;
  top: 8px;
  right: 8px;
  width: 24px;
  height: 24px;
  background: #409eff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.setting-item > span {
  font-size: 14px;
  color: #606266;
}

.value-label {
  margin-left: 8px;
  font-size: 12px;
  color: #909399;
}

.shortcut-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.shortcut-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #f5f7fa;
  border-radius: 4px;
  font-size: 13px;
  color: #606266;
}

.setting-actions {
  margin-top: 30px;
  display: flex;
  gap: 12px;
}

.setting-actions .el-button {
  flex: 1;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-header h4 {
  margin: 0;
}

.custom-shortcuts-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.custom-shortcut-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 8px;
  transition: all 0.3s;
  border: 1px solid transparent;
}

.custom-shortcut-item:hover {
  background: #ecf5ff;
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.shortcut-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  flex-shrink: 0;
}

.shortcut-info {
  flex: 1;
  min-width: 0;
}

.shortcut-name {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.shortcut-path {
  font-size: 12px;
  color: #909399;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.shortcut-actions {
  display: flex;
  gap: 4px;
  flex-shrink: 0;
}
</style>
